/*******************************************************************************
GThread.cpp

	Author:		LiuDingXi
	e-mail:		liudx@gmail.com
	Date time:	2010-06-07

	Copyright (C) 2010
	All rights reserved.
	
*******************************************************************************/
#include "StdAfx.h"
#include "GThread.h"

#if (_OS_ == _OS_WINNT_)
#define _POSIX_
#include <signal.h>
#include <fcntl.h>
#define SIGKILL	SIGTERM
#endif//PLATFORM_WIN32


#if (_OS_ == _OS_WINNT_)
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#endif//(_OS_ == _OS_WINNT_)


GLock::GLock()
{
	//m_mutex = NULL;
}

GLock::~GLock()
{

}

BOOL GLock::Create()
{
	return (0 == pthread_mutex_init(&m_mutex, NULL)) ? TRUE : FALSE;
}

BOOL GLock::Destroy()
{
	return (0 == pthread_mutex_destroy(&m_mutex)) ? TRUE : FALSE;
}

BOOL GLock::Lock()
{
	return (0 == pthread_mutex_lock(&m_mutex))  ? TRUE : FALSE;
}

BOOL GLock::Unlock()
{
	return (0 == pthread_mutex_unlock(&m_mutex)) ? TRUE : FALSE; 
}

//////////////////////////////////////////////////////////////////////////

#if (_OS_ == _OS_WINNT_)

GSemaphore::GSemaphore()
{
	m_sem = NULL;
}

GSemaphore::~GSemaphore()
{

}

BOOL GSemaphore::Create(LPCTSTR szName)
{
	return (0 == sem_init(&m_sem, 0, 0)) ? TRUE : FALSE;
}

BOOL GSemaphore::Destroy(LPCTSTR szName)
{
	return (0 == sem_destroy(&m_sem)) ? TRUE : FALSE;
}

SINT GSemaphore::Wait()
{
	return sem_wait(&m_sem);
}

SINT GSemaphore::Signal()
{
	return sem_post(&m_sem);
}

#endif //_OS_ == _OS_WINNT_

#if (_OS_ == _OS_IPHONE_)

GSemaphore::GSemaphore()
{
	m_psem = NULL;
}

GSemaphore::~GSemaphore()
{

}

BOOL GSemaphore::Create(LPCTSTR szName)
{
	m_psem = sem_open(szName, O_CREAT, 0, 0);
	if(m_psem == SEM_FAILED)
	{
		sem_unlink(szName);
		m_psem = sem_open(szName, O_CREAT, 0, 0);
	}
	return (m_psem == SEM_FAILED ? FALSE : TRUE);
}

BOOL GSemaphore::Destroy(LPCTSTR szName)
{
	if(m_psem)
	{
		sem_close(m_psem);
		sem_unlink(szName);
		m_psem = NULL;
		return TRUE;
	}
	return FALSE;
}

SINT GSemaphore::Wait()
{
	return sem_wait(m_psem);
}

SINT GSemaphore::Signal()
{
	return sem_post(m_psem);
}

#endif //_OS_ == _OS_IPHONE_
//////////////////////////////////////////////////////////////////////////

GThread::GThread()
{
}

GThread::~GThread()
{

}

BOOL GThread::Create(GThreadProc pfProc, VOID* pObject)
{
	return (0 == pthread_create(&m_thread, 0, pfProc, pObject)) ? TRUE : FALSE;
}

BOOL GThread::Destroy()
{
	void*	thread_ret = 0;
	pthread_kill(m_thread, SIGKILL);
	pthread_join(m_thread, &thread_ret);

	return TRUE;
}
